<template>
  <div class="app-container search-table-box aidex-table">
    <el-card shadow="never" ref="queryRef" style="margin-bottom: 12px;" class="search_card" v-show="showSearch">
      <div class="filter-container">
        <div class="search_box" style="padding-bottom: 16px">
          <el-form :model="queryParams" ref="queryForm" label-width="80px" size="mini">
            <el-row :gutter="2">
              <el-col :md="5" >
                <el-form-item prop="searchValues">
                  <el-select
                    v-model="queryParams.searchValues"
                    multiple
                    filterable
                    remote
                    reserve-keyword
                    clearable
                    placeholder="请输入物料编码/物料名称/规格型号"
                    :remote-method="remoteSearchValue"
                    @change="handleQuery"
                    :loading="remoteSearchValueLoading"
                    style="width: 415px;margin-left: -78px"
                  >
                    <el-option
                      v-for="item in searchValueOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                      :disabled="item.disabled">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :md="6" align="right">
                <el-form-item>
                  <el-button class="filter-item" type="primary" @click="handleQuery">搜索</el-button>
                  <el-button class="filter-item" style="margin-left: 8px" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
    </el-card>
    <el-card shadow="never" >
      <template #header>
        <el-row>
          <el-col :span="8">
            <div class="card-header">
              <el-button disabled type="text">物料信息</el-button>
            </div>
          </el-col>
          <el-col :span="16">
            <div class="btn_box" align="right" style="float: right;">
              <el-button
                class="filter-item"
                style="margin-left: 8px;"
                icon="el-icon-download"
                @click="handleExport"
                size="mini"
                v-hasPermi="['saleconfig:material:export']"
              >导出</el-button>
              <right-toolbar :showSearch.sync="showSearch" @showSearchFun="showSearchFun" @queryTable="getList"></right-toolbar>
            </div>
          </el-col>
        </el-row>
      </template>

      <el-table
              border
              stripe
              default-expand-all
              ref="tableRef"
              :key="tableKey"
              v-loading="loading"
              :data="materialList"
              @selection-change="handleSelectionChange"
              :row-style="rowClass"
              :header-cell-style= "{
                'font-size': '14px !important',
                'font-weight': '500 !important',
                'color': 'rgb(0 0 0)',
                'background-color': 'rgb(205 224 255)',
              }"
              highlight-current-row style="width: 100%;"
              :height="tableHeight"
      >
        <el-table-column label="序号" type="index" align="center" width="55">
          <template slot-scope="scope">
            <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
          </template>
        </el-table-column>
        <template v-for="item in columns">
<!--          <el-table-column label="公司" align="center" prop="siteName" width="160" v-if="item.visible && item.label=='客户产品'" show-overflow-tooltip/>-->
          <el-table-column label="物料编码" align="center" prop="materialCode" width="160" v-if="item.visible && item.label=='物料编码'" show-overflow-tooltip />
          <el-table-column label="物料名称" align="center" prop="materialName" width="220" v-if="item.visible && item.label=='物料名称'" show-overflow-tooltip />
          <el-table-column label="规格型号" align="center" prop="specificatCode" v-if="item.visible && item.label=='规格型号'" show-overflow-tooltip />
          <el-table-column label="颜色" align="center" prop="colorName" v-if="item.visible && item.label=='颜色'" show-overflow-tooltip />
          <el-table-column label="产品名称" align="center" prop="productName" width="200" v-if="item.visible && item.label=='产品名称'" show-overflow-tooltip />
          <el-table-column label="单位" align="center" prop="unitName" v-if="item.visible && item.label=='单位'" show-overflow-tooltip />
          <el-table-column label="单价" align="center" prop="price" v-if="item.visible && item.label=='单价'" show-overflow-tooltip />
          <el-table-column label="物料分类" align="center" prop="materialTypeName" v-if="item.visible && item.label=='物料分类'" show-overflow-tooltip />
          <el-table-column label="含税标识" align="center" prop="isTaxName" v-if="item.visible && item.label=='含税标识'" show-overflow-tooltip />
          <el-table-column label="税收分类" align="center" prop="taxName" v-if="item.visible && item.label=='税收分类'" show-overflow-tooltip />
          <el-table-column label="税收分类编码" align="center" prop="taxCode" v-if="item.visible && item.label=='税收分类编码'" show-overflow-tooltip width="180" />
          <el-table-column label="税率" align="center" prop="taxRateName" v-if="item.visible && item.label=='税率'" show-overflow-tooltip />
          <el-table-column label="备注" align="center" prop="remark" v-if="item.visible && item.label=='备注'" show-overflow-tooltip />
          <el-table-column label="状态" align="center" prop="statusName" v-if="item.visible && item.label=='状态'" show-overflow-tooltip />
          <el-table-column label="更新日期" align="center" prop="updateTime" width="160" v-if="item.visible && item.label=='更新日期'" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
        </template>

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" fixed="right">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-setting"
              type="text"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['saleconfig:material:edit']"
            >配置产品</el-button>
          </template>
        </el-table-column>
        <div slot="empty">
          <svg-icon icon-class="search-none" style="font-size: 64px;" />
          <p>暂无数据</p>
        </div>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改物料对话框 -->
      <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="1000px" top="10vh" append-to-body>
        <div style="height: 390px;overflow: auto; padding: 12px 24px;">
          <el-form ref="form" size="mini" :model="form" :rules="rules" label-position="right"  label-width="100px">
            <el-row :gutter="24">
<!--              <el-col :span="12">-->
<!--                <el-form-item label="客户产品" prop="siteName">-->
<!--                  <el-input v-model="form.siteName" placeholder="-" readonly/>-->
<!--                </el-form-item>-->
<!--              </el-col>-->
              <el-col :span="12">
                <el-form-item label="物料编码" prop="materialCode">
                  <el-input v-model="form.materialCode" placeholder="-" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="物料名称" prop="materialName">
                  <el-input v-model="form.materialName" placeholder="-" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="规格型号" prop="specificatCode">
                  <el-input v-model="form.specificatCode" placeholder="-" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="颜色" prop="colorName">
                  <el-input v-model="form.colorName" placeholder="-" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="单位" prop="unitName">
                  <el-input v-model="form.unitName" placeholder="-" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="单价" prop="price">
                  <el-input v-model="form.price" placeholder="-" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="物料分类" prop="materialTypeName">
                  <el-input v-model="form.materialTypeName" placeholder="-" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="含税标识" prop="isTaxName">
                  <el-input v-model="form.isTaxName" placeholder="-" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="税收分类" prop="taxName">
                  <el-input v-model="form.taxName" placeholder="-" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="税收分类编码" prop="taxCode">
                  <el-input v-model="form.taxCode" placeholder="-" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="税率" prop="taxRateName">
                  <el-input v-model="form.taxRateName" placeholder="-" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="form.remark" placeholder="-" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="状态" prop="statusName">
                  <el-input v-model="form.statusName" placeholder="-" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产品名称" prop="productName">
                  <el-input v-model="form.productName" maxlength = 0 clearable placeholder="请选择产品" >
                    <el-button slot="append" icon="el-icon-search" @click="openproductDialogOpen">
                    </el-button>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary"  size="mini" @click="submitForm">确 定</el-button>
          <el-button  size="mini" @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 编辑-产品-弹出查询 -->
      <el-dialog v-dialogDrag  :close-on-click-modal="false" title="编辑物料-产品选择" :visible.sync="productDialogOpen" width="1000px" append-to-body>
        <div class="dialog_box" style="height:550px;">
          <el-form label-position="left" :model="productQueryParams"  ref="productQueryForm" label-width="88px" >
            <el-form-item  prop="productSearchValue">
              <el-input
                v-model="productQueryParams.searchValue"
                size="mini"
                placeholder="请输入编码或名称查询产品"
                @keyup.enter.native="handleproductQuery"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleproductQuery">查询</el-button>
            </el-form-item>
          </el-form>
          <el-table v-loading="productSelectLoading" :data="productList"
                    height="400"
                    @row-click="handleproductRowClick"
                    ref="productSingleTable"
                    :row-key="getproductListRowKey"
                    :row-style="{height:2+'px'}"
                    :header-cell-style= "{
                        'font-size': '14px !important',
                        'font-weight': '500 !important',
                        'background-color':'rgb(241 241 241 / 52%)'
                      }"
                    :cell-style="{padding:'2px 4px'}"
                    border
                    @selection-change="handleproductSelectionChange">
            <el-table-column label="选择" width="60">
              　　　　<template slot-scope="scope">
              　　　　　　<el-radio v-model="productDialogRadio" :label="scope.row"><i></i></el-radio>
              　　　　</template>
              　　 </el-table-column>
            <!-- 数据 -->
            <el-table-column prop="productCode" label="货物及服务编码" width="200"></el-table-column>
            <el-table-column prop="productName" label="货物及服务名称" ></el-table-column>
            <el-table-column prop="isTaxName" label="含税" width="100"></el-table-column>
            <el-table-column prop="taxRateName" label="税率" width="80"></el-table-column>
            <el-table-column prop="price" label="单价" width="140">
              <template slot-scope="scope">
                <span v-if="scope.row.price && scope.row.price != 'NULL' "> {{scope.row.price | formatCurrency}} </span>
                <span v-else> - </span>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="productTotal>0"
            :total="productTotal"
            :page.sync="productQueryParams.pageNum"
            :limit.sync="productQueryParams.pageSize"
            @pagination="getproductList"
          />
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" type="primary" @click="confirmproduct">确 定</el-button>
          <el-button size="mini" @click="productCancel">取 消</el-button>
        </div>
      </el-dialog>


    </el-card>
  </div>
</template>

<script>
import { listMaterial, getMaterial, delMaterial, addMaterial, updateMaterial } from "@/api/saleconfig/material";
/* 产品列表 **/
import { listProduct } from "@/api/saleconfig/product";
/* 城市列表 **/
import { provinceList, cityList, districtList } from "@/api/system/city";

export default {
  name: "Material",
  dicts: ['is_tax', 'bas_common_status', 'tax_code', 'unit', 'tax_rate'],
  data() {
    return {
      advanced: false,
      tableHeight: this.getInitTableHeight(),
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料表格数据
      materialList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        params:{

        },
        materialId: null,
        parentMaterialId: null,
        custId: null,
        product: null,
        siteName: null,
        materialCode: null,
        materialName: null,
        specificatCode: null,
        colorCode: null,
        unit: null,
        materialType: null,
        isTax: null,
        taxCode: null,
        taxRate: null,
        status: null,
        createName: null,
        updateName: null,
        productName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      tableKey: 21,
      columnsKey: 'material',
      // 自定义列
      columns: [
          {
              key: 0,
              label: `客户产品`,
              visible: true
          },
          {
              key: 1,
              label: `物料编码`,
              visible: true
          },
          {
              key: 2,
              label: `物料名称`,
              visible: true
          },
          {
              key: 3,
              label: `规格型号`,
              visible: true
          },
          {
              key: 4,
              label: `颜色`,
              visible: true
          },
          {
              key: 5,
              label: `产品名称`,
              visible: true
          },
          {
              key: 6,
              label: `单位`,
              visible: true
          },
          {
              key: 7,
              label: `单价`,
              visible: true
          },
          {
              key: 8,
              label: `物料分类`,
              visible: true
          },
          {
              key: 9,
              label: `含税标识`,
              visible: true
          },
          {
              key: 10,
              label: `税收分类`,
              visible: true
          },
          {
              key: 15,
              label: `税收分类编码`,
              visible: true
          },
          {
              key: 11,
              label: `税率`,
              visible: true
          },
          {
              key: 12,
              label: `备注`,
              visible: true
          },
          {
              key: 13,
              label: `状态`,
              visible: true
          },
          {
              key: 14,
              label: `更新日期`,
              visible: true
          }
      ],
      // 远程查询条件加载
      remoteSearchValueLoading: false,
      // 关键字查询条件
      searchValueOptions:[

      ],

      /* ======================================编辑-产品选择======================================  */
      productname: null,
      productTotal: 0,
      productList: [],
      productDialogRadio: null,
      productDialogOpen: false,
      productSelectLoading: false,
      productQueryParams: {
          searchValue: null,
          pageNum: 1,
          pageSize: 20,
      },

      /* ======================================省市区======================================  */
      // 省
      provinceId: null,
      provinceList:[],
      // 市
      cityId: null,
      cityList:[],
      // 区
      districtId: null,
      districtList:[],

    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 行样式 */
    rowClass({ row, rowIndex }) {
      if (this.ids.includes(row.id)) {
          return { background: "#d9edf7", height:'20px' };
      } else {
          return { height:'20px'};
      }
    },
   /** 隐藏搜索按钮操作 */
   showSearchFun(isShowSearch){
      this.showSearch = isShowSearch
      let oldHeight = this.$refs.queryRef.$el.offsetHeight
      if(!isShowSearch){
          //当前是显示状态
          oldHeight = oldHeight + 12
      }else{
          oldHeight = oldHeight - 12
      }
      this.$nextTick(() => (
         this.tableHeight = this.$refs.tableRef.$el.offsetHeight - (this.$refs.queryRef.$el.offsetHeight-oldHeight)
      ))
    },
    /** 展开按钮操作 */
    toggleAdvanced() {
      const oldHeight = this.$refs.queryRef.$el.offsetHeight
      this.advanced = !this.advanced
      this.$nextTick(() => (
         this.tableHeight = this.$refs.tableRef.$el.offsetHeight - (this.$refs.queryRef.$el.offsetHeight-oldHeight)
      ))
    },
    /** 查询物料列表 */
    getList() {
      this.loading = true;
      listMaterial(this.queryParams).then(response => {
        this.materialList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productId: null,
        materialId: null,
        parentMaterialId: null,
        custId: null,
        product: null,
        siteName: null,
        materialCode: null,
        materialName: null,
        specificatCode: null,
        colorCode: null,
        colorName: null,
        unit: null,
        unitName: null,
        price: null,
        materialType: null,
        materialTypeName: null,
        isTax: null,
        isTaxName: null,
        taxCode: null,
        taxName: null,
        taxRate: null,
        taxRateName: null,
        remark: null,
        status: null,
        statusName: null,
        createName: null,
        createTime: null,
        updateName: null,
        updateTime: null,
        productName: null
      };
      this.resetForm("form");
    },


      /* ※※ 查询 省市区 相关方法 start ※※ */
      // 获取省
      getProvinceList(){
          provinceList().then(response => {
              this.provinceList = response.data;
          });
      },
      // 获取市
      getCityList(){
          console.log(this.provinceId);
          cityList( {"parentId" : this.provinceId } ).then(response => {
              this.cityList = response.data;
          });
      },
      // 获取区县
      getDistrictList(){
          districtList( {"parentId" : this.cityId } ).then(response => {
              this.districtList = response.data;
          });
      },
      // 选中省份
      handleChangeProvince(val){
          // 给表单省字段赋值
          this.form.provinceid = val;
          let province = {};
          province = this.provinceList.find((item)=>{
              return item.id === val;
          });
          this.form.province = province.name;
          // 城市数据清空、区县数据清空;
          this.cityList = [];
          this.districtList = [];
          // 已选市、区数据清空
          this.cityId = null;
          this.districtId = null;
          // 表单城市、区县数据清空
          this.form.cityid = null;
          this.form.city = null;
          this.form.areaid = null;
          this.form.area = null;
          // 获取城市数据
          this.getCityList();
      },
      // 清空省份
      handleClearProvince(){
          // 城市数据清空、区县数据清空;
          this.cityList = [];
          this.districtList = [];
          // 已选市、区数据清空
          this.cityId = null;
          this.districtId = null;
          // 表单城市、区县数据清空
          this.form.cityid = null;
          this.form.city = null;
          this.form.areaid = null;
          this.form.area = null;
      },
      // 选中城市
      handleChangeCity(val){
          // 给表单市字段赋值
          this.form.cityid = val;
          let city = {};
          city = this.cityList.find((item)=>{
              return item.id === val;
          });
          this.form.city = city.name;
          // 区县数据清空
          this.districtList = [];
          // 已选区县清空
          this.districtId = null;
          // 表单区县清空
          this.form.areaid = null;
          this.form.area = null;
          // 获取城市数据
          this.getDistrictList();
      },
      // 清空省份
      handleClearCity(){
          // 区县数据清空
          this.districtList = [];
          // 已选区县清空
          this.districtId = null;
          // 表单区县清空
          this.form.areaid = null;
          this.form.area = null;
      },
      // 选中区县
      handleChangeDistrict(val){
          // 给表单省字段赋值
          this.form.areaid = val;
          let district = {};
          district = this.districtList.find((item)=>{
              return item.id === val;
          });
          this.form.area = district.name;
      },
      // 清空省份
      handleClearDistrict(){
          // 表单区县清空
          this.form.areaid = null;
          this.form.area = null;
      },

      /* ※※ 查询 省市区 相关方法 end ※※ */




    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物料";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMaterial(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改物料";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMaterial(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMaterial(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除物料编号为"' + ids + '"的数据项？').then(function() {
        return delMaterial(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('saleconfig/material/export', {
        ...this.queryParams
      }, `material_${new Date().getTime()}.xlsx`)
    },

      /** 动态加载关键字查询条件 */
      remoteSearchValue(query) {
          this.remoteSearchValueLoading = true;
          if (query !== '') {
              this.searchValueOptions = [
                  {value: '物料编码:' + query ,label: '物料编码:' + query },
                  {value: '物料名称:' + query ,label: '物料名称:' + query },
                  {value: '规格型号:' + query ,label: '规格型号:' + query },
              ];
              this.searchValueOptions.map(item => {
                  this.queryParams.searchValues.map((item2, index) => {
                      if(item.value.startsWith('物料编码') && item2.startsWith('物料编码')){
                          item.disabled = true;
                      }
                      if(item.value.startsWith('物料名称') && item2.startsWith('物料名称')){
                          item.disabled = true;
                      }
                      if(item.value.startsWith('规格型号') && item2.startsWith('规格型号')){
                          item.disabled = true;
                      }
                  })
              });
          } else {
              this.searchValueOptions = [];
          }
          this.remoteSearchValueLoading = false;
      },

      /* ※※ 编辑 客户产品代码 相关方法 start ※※ */
      /** ① 弹出编辑内容-客户产品代码 */
      openproductDialogOpen(){
          this.productDialogOpen = true;
          this.getproductList();
      },
      /** ② 单击行 **/
      handleproductRowClick(row, column, event){
          this.$refs.productSingleTable.toggleRowSelection(row);
      },
      /** ③ 行KEY **/
      getproductListRowKey(row) {
          return row.companycode
      },
      /** ④ 选中客户产品代码 **/
      handleproductSelectionChange(selection) {
          if (selection[0]) {
              this.productDialogRadio = selection[0]
              this.form.productId = selection[0].productId;
              this.form.productName = selection[0].productName;
          }
      },
      /** ⑤ 点击查询按钮 **/
      handleproductQuery(){
          this.productQueryParams.pageNum = 1;
          this.getproductList();
      },
      /** ⑥ 查询 **/
      getproductList(){
          this.productSelectLoading = true;
          listProduct(this.productQueryParams).then(response => {
              this.productList = response.rows;
              this.productTotal = response.total;
              this.productSelectLoading = false;
          });
      },
      /** ⑦ 点击确认查询 **/
      confirmproduct() {
          this.productCancel();
      },
      /** ⑧ 点击关闭查询弹出框 **/
      productCancel() {
          this.productDialogOpen = false;
      },
      /* ※※ 编辑 客户产品代码 相关方法 end ※※ */

  }
};
</script>
